<?php

defined('SYSPATH') or die('No direct script access.');

class Controller_Ftp extends Controller_Templates {
    
    public $ftp = NULL;

    public function action_index() {

        $this->template->title = __('Login');
        $this->template->content = View::factory('login');
    }

    public function action_login() {
        if ($this->request->is_ajax()) {
            // Para que no cargue el template
            $this->auto_render = FALSE;
            
            $res = $this->_connect($_POST['server'], $_POST['username'], $_POST['password'], $_POST['port']);

            if ($res) {

                // Guardo estos datos en session para futuras conecciones
                $ftp = array(
                    'hostname' => $_POST['server'],
                    'username' => $_POST['username'],
                    'password' => $_POST['password'],
                    'port' => $_POST['port']
                );
                Session::instance('native')->set('ftpInstance', $ftp);

                echo json_encode(array('res' => TRUE));
            } else {
                echo json_encode(array('res' => FALSE, 'msg' => __('Error al intentar conectar.')));
            }
        }
    }

    public function action_listFiles() {
        if ($this->request->is_ajax()) {
            $path = ($this->request->param('id')) ? $this->request->param('id') : '/';
            $view = View::factory('ftp');
            
            $ftp = Session::instance('native')->get('ftpInstance');
            $this->_connect($ftp);
            $view->set('files', $this->ftp->list_files($path));
        }
    }

    public function action_close() {
        $this->ftp->close();
    }

    private function _connect($host, $user, $pass, $port) {
        // Cargo la classe FTP
        require_once Kohana::find_file('vendors', 'ftp');
        $ftp = new FTP();
        
        if (is_array($host)) {
            $ftp->connect($host);
        } else {
            $ftp->hostname = $host;
            $ftp->username = $user;
            $ftp->password = $pass;
            $ftp->port = $port;
            $ftp->connect();
        }
        $this->ftp = $ftp;
    }

}